﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Data;
using System.Data.Entity;

using CooWork.Services;
using CooWork.Models;
using Coowork.Data.Mapping;

namespace CooWork.Controllers
{
    public class CotdController : BaseController
    {
        private CooWorkEntities context = new CooWorkEntities();
        //
        // GET: /Cotd/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult department()
        {
            return View();
        }

        public ActionResult usera()
        {
            return View();
        }

        [HttpPost]
        public ActionResult usera(Account model)
        {
            if (ModelState.IsValid)
            {
                int cid = UserService.UcId();
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                MembershipUser mu = Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                ProfileCommon profile = ProfileCommon.Create(model.UserName, true) as ProfileCommon;
                profile.DepartmentId = model.DepartmentId;             
                profile.Email = model.Email;
                profile.CompanyId = cid;
                profile.Save();

                Roles.AddUserToRole(model.UserName, model.Role);

                UserService.updateUserInfo(cid, model.DepartmentId, model.ActualName, (Guid)mu.ProviderUserKey);

                if (createStatus == MembershipCreateStatus.Success)
                {                   
                    return RedirectToAction("userlist", "Cotd");
                }
                else
                {
                    ModelState.AddModelError("",createStatus.ToString());
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);

        }


        public ActionResult usere()
        {
            Guid gid = UserService.Ugid();
            Account a = new Account();
            aspnet_Users au = context.aspnet_Users.Single(x => x.UserId == gid);
            MembershipUser mu = Membership.GetUser();
            a.ActualName = au.ActualName;
            a.DepartmentId = au.did.Value;
            a.Email = mu.Email;
            a.Role = Roles.GetRolesForUser()[0];
            a.UserName = au.UserName;
            return View(a);
        }

        [HttpPost]
        public ActionResult usere(Account model)
        {         
            Guid gid = UserService.Ugid();
            aspnet_Users au = context.aspnet_Users.Single(x => x.UserId == gid);
            MembershipUser mu = Membership.GetUser();
            mu.Email = model.Email;
            Membership.UpdateUser(mu);
            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                string newpwd = mu.ResetPassword();
                mu.ChangePassword(newpwd, model.Password);
            }            

            au.ActualName = model.ActualName;
            au.did = model.DepartmentId;
            context.Entry(au).State = EntityState.Modified;
            context.SaveChanges();

      

            if (!Roles.GetRolesForUser().Contains(model.Role))
            {
                string[] rolelist = Roles.GetRolesForUser();
                Roles.RemoveUserFromRoles(model.UserName, rolelist);
                Roles.AddUserToRole(model.UserName, model.Role);
            }

            return RedirectToAction("userlist", "Cotd");

          //  return View();
        }

        public ActionResult userlist()
        {
            var clist = UserService.GetCUserList(UserService.UcId(), false);
            return View(clist);
        }




        [HttpPost]
        public JsonResult reg(string cname,string ActualName,string username,string Email,string pwd)
        {
            Company cp = new Company();
            cp.cname = cname;
            context.Companies.Add(cp);
            context.SaveChanges();

            Department dt = new Department();
            dt.DepartmentName = cname;
            dt.cid = cp.ID;
            context.Departments.Add(dt);
            context.SaveChanges();

            MembershipCreateStatus createStatus;
            MembershipUser mu= Membership.CreateUser(username, pwd, Email, null, null, true, null, out createStatus);
            ProfileCommon profile = ProfileCommon.Create(username, true) as ProfileCommon;
            profile.DepartmentId =dt.ID;         
            profile.Email = Email;
            profile.CompanyId =cp.ID;
            profile.Save();

            cp.sadmin = (Guid)mu.ProviderUserKey;
            dt.Leader = (Guid)mu.ProviderUserKey;
            context.Entry(cp).State = EntityState.Modified;
            context.Entry(dt).State = EntityState.Modified;
            context.SaveChanges();
            UserService.updateUserInfo(cp.ID, dt.ID, ActualName, dt.Leader.Value);


            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(username, false /* createPersistentCookie */);                
            }
               

            return new JsonResult { Data = "ok" };
        }



    }
}
